package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.ILock;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private ILock simpleRedisLock;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private BlockingQueue<VoucherOrder> blockingQueue=new ArrayBlockingQueue<>(1024*1024);
    private static final ExecutorService SECKILL_ORDER_EXECUTOR= Executors.newSingleThreadExecutor();
    private static final DefaultRedisScript<Long> SECKILL_SCRIP;
    static {
        SECKILL_SCRIP=new DefaultRedisScript<>();
        SECKILL_SCRIP.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIP.setResultType(Long.class);
    }
    private VoucherOrderServiceImpl proxy;

    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(()->{
            while (true){
                try {
                    List<MapRecord<String, Object, Object>> mapRecords = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1")
                            , StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2))
                            , StreamOffset.create(STREAM_ORDER_KEY, ReadOffset.lastConsumed()));
                    if(mapRecords==null||mapRecords.isEmpty()){
                        continue;
                    }
                    MapRecord<String, Object, Object> record = mapRecords.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), false);
                    proxy.createVoucherOrder(voucherOrder);
                    //确认消息
                    stringRedisTemplate.opsForStream().acknowledge(STREAM_ORDER_KEY,"g1",record.getId());
                } catch (Exception e) {
                    log.error("优惠券订单处理异常",e);
                    handlePendingList();
                }
            }
        });
    }

    private void handlePendingList() {
        while (true){
            try {
                List<MapRecord<String, Object, Object>> mapRecords = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1")
                        , StreamReadOptions.empty().count(1)
                        , StreamOffset.create(STREAM_ORDER_KEY, ReadOffset.from("0")));
                if(mapRecords==null||mapRecords.isEmpty()){
                    break;
                }
                MapRecord<String, Object, Object> record = mapRecords.get(0);
                Map<Object, Object> value = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), false);
                proxy.createVoucherOrder(voucherOrder);
                //确认消息
                stringRedisTemplate.opsForStream().acknowledge(STREAM_ORDER_KEY,"g1",record.getId());
            } catch (Exception e) {
                log.error("优惠券pending-list订单处理异常",e);
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.execute(SECKILL_SCRIP
                , Arrays.asList(SECKILL_STOCK_KEY + voucherId, SECKILL_ORDER_KEY + voucherId)
                , userId.toString());
        int r = result.intValue();
        if(r!=0){
            return Result.fail(r==1? "库存不足":"不能重复下单");
        }
        long orderId = redisIdWorker.generateId("voucherOrder");
        //获得当前代理对象
        proxy= (VoucherOrderServiceImpl) AopContext.currentProxy();
        //把订单信息放入stream队列
        Map<String,String> map=new HashMap<>();
        map.put("id",String.valueOf(orderId));
        map.put("userId",userId.toString());
        map.put("voucherId",voucherId.toString());
        stringRedisTemplate.opsForStream().add(STREAM_ORDER_KEY,map);
        return Result.ok(orderId);
    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder){
        //判断用户是否已下单
        Long count = query().eq("user_id", voucherOrder.getUserId()).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if(count>0){ //一人一单
            log.error("用户重复下单！");
            return ;
        }
        boolean success = seckillVoucherService.update().setSql("stock=stock-1")
                .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock",0).update();//乐观锁（改进）解决线程安全
        if(!success){
            log.error("库存不足！");
            return ;
        }
        save(voucherOrder);
    }

//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        if(seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
//            return Result.fail("秒杀还未开始！");
//        }
//        if(seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
//            return Result.fail("秒杀已结束！");
//        }
//        if(seckillVoucher.getStock()<1){
//            return Result.fail("库存不足！");
//        }
//        //获得当前代理对象
//        VoucherOrderServiceImpl proxy = (VoucherOrderServiceImpl) AopContext.currentProxy();
//        Long userId = UserHolder.getUser().getId();
//        //获取分布式锁
//        RLock lock = redissonClient.getLock("lock:voucherOrder:" + userId);
//        boolean isLock = lock.tryLock();
//        if(!isLock){
//            return Result.fail("不能重复下单！");
//        }
//        try {
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            //释放分布式锁
//            lock.unlock();
//        }
////        synchronized (userId.toString().intern()) { //先加锁，再开启提交事务。toString是只看数字；intern()方法会从常量池中找一个与userId一样的字符串常量，并返回地址
////            return proxy.createVoucherOrder(voucherId);
////        }
//    }
}
